<template>
  <div class="order_detail">
    <van-nav-bar title="订单详情" left-text="" left-arrow @click-left="$router.go(-1)" />

    <div class="order_status" :style="`color:${color[obj.sign]};`">
      {{ status[obj.sign] }}
    </div>

    <div class="product">
      <van-cell-group inset>
        <van-cell title-class="shopname">
          <template #title>
            <img src="../assets/img/local.png" />
            <span>{{ get_shops.address }}</span>
          </template>
        </van-cell>
        <van-cell class="card" v-for="(goods, index2) in obj.order_details" :key="index2">
          <van-card :num="goods.quantity" :desc="goods.product_describe" :title="goods.product_name" :thumb="domain + goods.cover_url">
            <template #price>
              <div class="price">
                ￥
                <span>{{ goods.sale_price }}</span>
              </div>
            </template>
          </van-card>
        </van-cell>
        <van-cell title="" :value="`总计：￥${obj.pay_amount}`" title-class="time" value-class="total" />
      </van-cell-group>
    </div>

    <div class="info">
      <van-cell-group v-if="!isEdit" class="group" inset>
        <van-cell title="配送信息" />
        <van-cell class="info_title" title="配送地址" :value="obj.alls" :border="false" />
        <van-cell class="info_title" title="配送时间" :value="obj.receive_time" :border="false" />
        <van-cell class="info_title" title="订单号码" :value="obj.orderno" :border="false" />
        <van-cell class="info_title" title="订单时间" :value="obj.time" :border="false" />

        <van-cell class="btn" :border="false">
          <template #title>
            <van-button type="primary" size="small" round plain @click="showkefu = !showkefu">联系客服</van-button>
            <van-button v-if="obj.sign == 2 || obj.sign == 3" type="primary" size="small" round plain @click="onCancelOrder(obj)">撤销订单</van-button>
            <van-button v-if="obj.sign == 2 || obj.sign == 3" type="primary" size="small" round plain @click="showEdit">修改订单</van-button>
            <van-button v-if="obj.sign == 4" type="primary" size="small" round plain @click="oneMore(obj)">再来一单</van-button>
            <van-button v-if="obj.sign == 6" type="primary" size="small" round plain @click="cancelRefund(obj)">取消退款</van-button>
          </template>
        </van-cell>
      </van-cell-group>

      <van-cell-group v-if="isEdit" inset>
        <van-cell title="配送信息" />
        <van-field v-model="receive_name" label="下单姓名" placeholder="请填写下单姓名" input-align="right" />
        <van-field v-model="r_phone" type="tel" label="联系电话" placeholder="请填写联系电话" input-align="right" />
        <van-field v-model="r_address" label="配送地址" placeholder="请填写配送地址" input-align="right" />
      </van-cell-group>

      <van-cell-group v-if="isEdit" inset>
        <van-field v-model="receive_time_show" label="配送时间" placeholder="请选择配送时间" input-align="right" is-link readonly @click="showPicker = true" />
      </van-cell-group>
    </div>

    <div class="footer" v-if="isEdit">
      <van-button type="primary" block round plain @click="cancelEdit">取消修改</van-button>
      <van-button type="primary" block round @click="onEdit">确认修改</van-button>
    </div>

    <van-popup v-model="showPicker" position="bottom" round :style="{ height: '45%' }">
      <van-datetime-picker v-model="currentDate" type="datetime" :formatter="formatter" :filter="filterDate" :min-date="minDate" :max-date="maxDate" @confirm="onConfirm" @cancel="showPicker = false" />
    </van-popup>

    <van-popup v-model="showkefu" round closeable>
      <img class="kefu" :src="domain + kefu" />
    </van-popup>
  </div>
</template>

<script>
import { Dialog } from "vant"
import { Toast } from "vant"

export default {
  data () {
    return {
      obj: {},
      get_shops: {},
      shop: {},
      status: { 1: "待支付", 2: "待配送", 3: "配送中", 4: "已完成", 6: "撤销中", 7: "已撤销", },
      color: { 2: "#000", 3: "#DB5310", 4: "#5f5f5f", 6: "#DB5310", 7: "#000" },
      isEdit: false,
      minDate: null,
      maxDate: null,
      currentDate: new Date(),
      showPicker: false,

      receive_time_show: "",
      receive_time: "",
      receive_name: "",
      r_phone: "",
      r_address: "",

      kefu: this.$store.state.shop.kefu_image,
      showkefu: false,
    }
  },
  created () {
    this.setDynamicTimeRange()
    this.getDetail()
  },
  computed: {
    formattedMaxHourMin () {
      const [hour, minute] = this.shop.dinner[1].split(":").map(Number)
      return new Date(0, 0, 0, hour, minute)
    },
  },
  methods: {
    getDetail () {
      this.$axios
        .get(this.$api.getofflineorderdetail, {
          params: {
            order_id: this.$route.query.id,
          },
        })
        .then(res => {
          if (res.data.code == 1) {
            this.obj = res.data.data
            this.get_shops = res.data.data.get_shops
            this.obj.time = this.$dayjs(this.obj.order_time * 1000).format("YYYY-MM-DD HH:mm")
            this.obj.receive_time = this.$dayjs(this.obj.receive_time * 1000).format("YYYY-MM-DD HH:mm")
            this.obj.sign = this.obj.order_status
            this.obj.alls = this.obj.r_address + " " + this.obj.r_phone + " " + this.obj.receive_name
          }
        })
    },
    formatter (type, value) {
      if (type === "year") return ""
      if (type === "month") return `${value}月`
      if (type === "day") return `${value}日`
      if (type === "hour") return `${value}点`
      if (type === "minute") return `${value}分`
      return value
    },
    filterDate (type, options) {
      if (type === "hour") {
        const currentHour = new Date().getHours()
        const currentMinute = new Date().getMinutes()
        let curr = 60 - currentMinute
        if (curr < 30) options = options.filter(item => item != currentHour)
        return options.filter(option => option <= this.maxHour && option >= this.minHour)
      }
      if (type === "minute") {
        return options.filter(option => option % 30 === 0)
      }
      return options
    },
    setDynamicTimeRange () {
      this.shop = this.$store.state.shop
      const now = new Date()
      const maxDaysLater = new Date(now)
      maxDaysLater.setDate(now.getDate() + this.shop.ahead_days)
      this.minDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes())
      this.maxDate = new Date(maxDaysLater.getFullYear(), maxDaysLater.getMonth(), maxDaysLater.getDate(), this.formattedMaxHourMin.getHours(), this.formattedMaxHourMin.getMinutes())
      this.minHour = this.shop.lunch[0].split(":").map(Number)[0]
      this.maxHour = this.shop.dinner[1].split(":").map(Number)[0]
    },
    onConfirm (val) {
      let selectedDate = new Date(val)
      let hour = selectedDate.getHours()
      let minute = selectedDate.getMinutes()
      let adjustedMinute = minute >= 30 ? 30 : 0
      let adjustedDate = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), selectedDate.getDate(), hour, adjustedMinute, 0, 0)
      let show = this.$dayjs(adjustedDate).format("YYYY年MM月DD日 HH:mm")
      this.receive_time_show = show
      this.receive_time = Math.floor(adjustedDate.getTime() / 1000)
      this.showPicker = false
    },
    cancelEdit () {
      this.isEdit = false
      this.getDetail()
    },
    onEdit () {
      if (this.receive_name !== "" && this.r_phone !== "" && this.r_address !== "" && this.receive_time_show !== "") {
        this.$axios
          .post(this.$api.UserEditOrder, {
            order_id: this.obj.order_id,
            receive_name: this.receive_name,
            r_phone: this.r_phone,
            r_address: this.r_address,
            receive_time: this.receive_time,
          })
          .then(res => {
            if (res.data.code == 1) {
              this.isEdit = false
              this.getDetail()
            } else {
              Toast.fail(res.data.msg)
            }
          })
      } else {
        Toast.fail("缺少收货信息")
      }
    },
    oneMore () {
      this.$router.push('/')
    },
    showEdit () {
      this.receive_name = this.obj.receive_name
      this.r_phone = this.obj.r_phone
      this.r_address = this.obj.r_address
      this.receive_time_show = this.obj.receive_time
      this.receive_time = this.$dayjs(this.obj.receive_time).unix()
      this.isEdit = true
    },
    onCancelOrder (item) {
      Dialog.confirm({
        title: "提示",
        message: "确认撤销订单？",
      })
        .then(() => {
          this.$axios
            .post(this.$api.usercancel, {
              order_id: item.order_id,
            })
            .then(res => {
              if (res.data.code == 1) {
                this.$router.go(-1)
              } else {
                Toast.fail("操作失败")
              }
            })
        })
        .catch(() => {
          // on cancel
        })
    },
    cancelRefund (item) {
      Dialog.confirm({
        title: "提示",
        message: "确认取消退款？",
      })
        .then(() => {
          this.$axios
            .post(this.$api.usercanceloperation, {
              order_id: item.order_id,
            })
            .then(res => {
              if (res.data.code == 1) {
                this.$router.go(-1)
              } else {
                Toast.fail("操作失败")
              }
            })
        })
        .catch(() => {
          // on cancel
        })
    },
  },
}
</script>

<style lang="less" scoped>
.order_detail {
  padding-bottom: 70px;

  .order_status {
    font-size: 20px;
    color: #272727;
    font-weight: bold;
    padding: 16px 16px 25px;
    text-align: center;
  }

  .van-cell-group {
    margin: 0 10px 16px;
  }

  .product {
    .shopname {
      display: flex;
      align-items: center;
      flex: 4;

      img {
        margin-right: 10px;
        filter: grayscale(100%);
      }
    }

    .status {
      color: #5f5f5f;
      font-size: 16px;
      font-weight: bold;
    }

    .card {
      .van-card {
        padding: 0;
        background-color: #fff;

        .van-card__title {
          color: #494b4e;
          font-size: 16px;
          margin-bottom: 4px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
        }

        .price {
          color: #5f5f5f;
          font-size: 16px;
          font-weight: bold;
        }
      }
    }

    .time {
      color: #999999;
      font-size: 12px;
    }

    .total {
      color: #494b4e;
      font-size: 14px;
      font-weight: bold;
    }
  }

  .info {
    .group {
      padding-bottom: 10px;
    }

    .info_title {
      padding-bottom: 0;

      .van-cell__value {
        flex: 3;
        text-align: left;
      }
    }

    .btn {
      text-align: right;
      padding-top: 26px;

      .van-button {
        margin-left: 10px;
      }
    }
  }

  .footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    width: calc(100% - 32px);
    padding: 16px;

    .van-button {
      flex: 1;
    }

    .van-button:not(:first-child) {
      margin-left: 10px;
    }
  }

  .kefu {
    display: block;
    width: 300px;
    height: 300px;
  }
}
</style>
